Object Oriented Programming and Design with Java 20CS43P
COMPUTER SCIENCE &
ENGG SJP-BANGALORE BHASKAR M-
LECTURER
Benefits of Single Responsibility Principle
• When an application has multiple
classes,
each of them following
this principle, then
the
applicable becomes more maintainable, easier to understand.
• The code quality
of the application is
better,
thereby having
fewer defects.
• Onboarding new
members are easy, and they can
start contributing
much faster.
• Testing and writing test cases
is much
simpler
Example: CALCULATOR PROGRAM
class Calculator {
// this class is
responsible for Arithmetic operations & printing Values
public static int add(int x, int y) { return x +
y; }
public static int sub(int x, int y) { return x - y; }
public static int mul(int x, int y) { return x * y; }
public static int div(int x, int y) { return x /
y; }
public static void display(int value)
{
System.out.println("The value is="+value);
}
}
class CalcDemo1
{
public static void main(String args[])
{
int a = Calculator.add(20, 30);
Calculator.display(a);
int b = Calculator.sub(20, 30);
Calculator.display(b);
int c = Calculator.mul(20, 30);
Calculator.display(c);
int d = Calculator.div(20, 30);
Calculator.display(d);
}
}
The above program violates SRP, since the class
Calculator has 2
responsibilities Arithmetic operations
& printing Values
To maintain SRP we have to write the program so
that the class should have only one responsibility.
class Calculator1
{ // this class is only responsible for
Arithmetic operations
public static int add(int x, int y) { return x +
y; }
public static int sub(int x, int y) { return x - y; }
public static int mul(int x, int y) { return x * y; }
public static int div(int x, int y) { return x /
y; }
}
class ResultPrinter
{ // this class is only responsible for printing
int values
public static void printResult(int value)
{
System.out.println("The value is="+value);
}
}